import { IsOptionsStatus, isOptionsStatusByIndexPayload, isPicLink, IsTypeStatus } from '@/types';
import type { EditorStore, MaterialStore, OptionsStatus, PicLink, TypeStatus } from '@/types';

/*
 * @Author: jhw
 * @Date: 2025-08-15 14:15:44
 * @LastEditors: jhw
 * @LastEditTime: 2025-08-15 15:37:54
 * @Description:
 */
export const dispatch = (
  Store: MaterialStore | EditorStore,
  Status: OptionsStatus | TypeStatus,
  configKey: string,
  payload?: number | string | boolean | PicLink,
) => {
  // 修改仓库中的状态
  switch (configKey) {
    case 'title':
    case 'desc':
    case 'titleColor':
    case 'descColor': {
      if (typeof payload !== 'string') {
        throw new Error(`Invalid payload type for ${configKey}. Expected string.`);
      }
      Store.setTextStatus(Status[configKey], payload);
      break;
    }
    case 'options': {
      if (IsOptionsStatus(Status)) {
        if (typeof payload === 'number') {
          // 删除选项
          Store.removeOptionsStatus(Status[configKey], payload);
          return;
        } else if (typeof payload === 'object' && isPicLink(payload)) {
          // 设置图片链接
          Store.setPicLinkByIndex(Status[configKey], payload);
        } else if (typeof payload === 'object' && isOptionsStatusByIndexPayload(payload)) {
          // 设置选项
          Store.setOptionsStatusByIndex(Status[configKey], payload);
        } else if (typeof payload === 'boolean') {
          Store.setUse(Status[configKey], payload);
        } else {
          // 添加选项-status数组中是 数组类型的
          Store.setOptionsStatus(Status[configKey]);
        }
      }

      break;
    }
    case 'position': {
      if (typeof payload !== 'number') {
        throw new Error(`Invalid payload type for ${configKey}. Expected number.`);
      }
      Store.setPositionStatus(Status[configKey], payload);
      break;
    }
    case 'titleSize':
    case 'descSize':
    case 'titleWeight':
    case 'descWeight':
    case 'titleItalic':
    case 'descItalic': {
      if (typeof payload !== 'number') {
        throw new Error(`Invalid payload type for ${configKey}. Expected number.`);
      }
      Store.setSizeStatus(Status[configKey], payload);
      break;
    }
    case 'type': {
      if (typeof payload !== 'number') {
        throw new Error(`Invalid payload type for ${configKey}. Expected number.`);
      }
      if (IsTypeStatus(Status)) {
        // 判断是否是note-desc组件
        if (Status[configKey].name === 'note-desc') {
          Store.setNoteDescTypeStatus(Status, payload);
        } else {
          Store.setTypeStatus(Status[configKey], payload);
        }
      }
      break;
    }
    case 'isRequire': {
      if (typeof payload !== 'number') {
        throw new Error(`Invalid payload type for ${configKey}. Expected number.`);
      }
      if (IsOptionsStatus(Status)) {
        Store.setSwitchStatus(Status[configKey]!, payload);
      }
      break;
    }
  }
};
